package srv

import (
	"arc_srv4/common"
	"arc_srv4/logutils"
	"arc_srv4/middleware"
	"arc_srv4/utils"
	"github.com/kataras/iris/v12"
	"go.uber.org/zap"
	"time"
)

func GetToken(ctx iris.Context) {
	params := new(common.TokenReq)
	// 判断参数是否错误
	if err := ctx.ReadJSON(&params); err != nil {
		// 参数错误
		//ctx.StatusCode(iris.StatusInternalServerError)
		_, _ = ctx.JSON(common.ApiNoDataResponse(common.Http10006, common.Http10006Desc))
	} else {
		// 检查appKey和secret有效性
		appKey, appSecret := params.AppKey, params.AppSecret
		res := middleware.CheckUser(appKey, appSecret)

		if res.IB != 200 {
			logutils.Logger.Info("check user error", zap.String("appKey", appKey), zap.String("appSecret", appSecret), zap.Int("res.IB", res.IB), zap.String("res.Message", res.Message))
			_, _ = ctx.JSON(common.ApiNoDataResponse(res.IB, res.Message))
			return
		}

		// 判断调用次数
		ib := middleware.CheckApiTimes(appKey, ctx.Path())
		if ib.IB != 200 {
			_, _ = ctx.JSON(common.ApiRspOnly{Code: ib.IB, Message: ib.Message})
			return
		}

		logutils.Logger.Info("check user success", zap.String("appKey", appKey), zap.String("appSecret", appSecret), zap.Int("res.IB", res.IB), zap.String("res.Message", res.Message))
		// 生成token
		tokenData := new(common.TokenData)

		// 数据库设置token有效时间长度 默认单位s
		expire := middleware.GetExpired(appKey)
		token, err := middleware.GenToken(common.JwtCfg.Secret, appKey, expire)
		if err != nil {
			logutils.Logger.Info("generate token error", zap.String("appKey", appKey), zap.String("appSecret", appSecret), zap.Error(err))
			_, _ = ctx.JSON(common.ApiNoDataResponse(common.Http10006, common.Http10006Desc))
			return
		}
		logutils.Logger.Info("generate token success", zap.String("appKey", appKey), zap.String("appSecret", appSecret))

		// 返回消息
		tokenData.Token = token
		expired := time.Now().Add(time.Duration(expire) * time.Second).Unix()
		tokenData.Expired = expired
		utils.RedisSet(appKey, token, expire)

		// 写入次数
		_ = middleware.InsertTimes(appKey, ctx.Path())
		logutils.Logger.Info("insert times success", zap.String("appKey", appKey))
		ctx.Next()

		logutils.Logger.Info("get token success", zap.String("appKey", appKey), zap.String("appSecret", appSecret))
		_, _ = ctx.JSON(common.ApiResponse(common.Http200, tokenData, common.Http200Desc))
	}
}
